package test.chat.client.view;

import test.chat.client.websockets.ChatService;
import test.chat.common.command.MessageCommand;

import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.Widget;

public class ChatView extends Composite {
    MyUiBinder binder = GWT.create(MyUiBinder.class);

    interface MyUiBinder extends UiBinder<Widget, ChatView> {/*empty*/}

    @UiField
    FlowPanel messagesPanel;

    @UiField
    TextArea textArea;

    @UiField
    ScrollPanel scrollPanel;

    ChatService chatService;

    public ChatView(ChatService chatService) {
        initWidget(binder.createAndBindUi(this));

        this.chatService = chatService;
    }

    @UiHandler(value="textArea")
    public void onKeyDown(KeyDownEvent event) {
        if(event.isControlKeyDown() && event.getNativeKeyCode() == KeyCodes.KEY_ENTER) {
            MessageCommand command = new MessageCommand();

            command.setMessageText(textArea.getText());

            chatService.sendCommand(command);

            textArea.setText("");
        }
    }

    public void addMessage(MessageCommand command) {
        messagesPanel.add(new Label(command.getFromUser() + " : " + command.getMessageText()));

        scrollPanel.scrollToBottom();
    }
}
